package com.kingdee.pda.ui.pick_goods;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.basecommon.http.MyObserver;
import com.example.basecommon.http.RxHelper;
import com.example.basecommon.http.rxjava.BaseResponse;
import com.example.basecommon.http.rxjava.HttpUtils;
import com.example.basecommon.utils.ConstantUtil;
import com.example.basecommon.utils.SpeakUtils;
import com.kingdee.pda.Api;
import com.kingdee.pda.R;
import com.kingdee.pda.entity.Warehouse;
import com.kingdee.pda.ui.activity.BaseTitleActivity;
import com.kingdee.pda.ui.activity.SettingActivity;
import com.kingdee.pda.ui.dialog.RemindDialog;
import com.kingdee.pda.ui.out_check.OutCheckActivity;
import com.kingdee.pda.util.CommonUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * PDA拣选详情
 * Created by dlj
 * DATE 2022/5/23
 */
public class PickGoodsDetailActivity extends BaseTitleActivity implements View.OnKeyListener {
    private EditText et_locationCode, et_skuCode, et_number;
    private Button btn_confirm, btn_submit;
    private RecyclerView recyclerView;
    private PickGoodListAdapter adapter;
    private PickOrderBean pickOrderBean;

    private int pickType;//拣选数量框类型  0 匹配扫描  1 逐件扫描
    private PickOrderBean.SkuBean selectedSkuBean;
    private boolean isComplete = false;
    private int pickQty = 0, pickedQty = 0;

    @Override
    protected void onActivityCreate(Bundle savedInstanceState) {
        super.onActivityCreate(savedInstanceState);
        setContentView(R.layout.activity_pickgoods_detail);
    }

    @Override
    protected void initView() {
        super.initView();

        pickOrderBean = (PickOrderBean) getIntent().getSerializableExtra("pickOrderBean");

        if (pickOrderBean == null) return;

        setTitle(pickOrderBean.getBillNo());
        et_locationCode = findViewById(R.id.et_locationCode);
        et_skuCode = findViewById(R.id.et_skuCode);
        et_number = findViewById(R.id.et_number);
        setEditTextScannerEvents(et_locationCode, this);
        setEditTextScannerEvents(et_skuCode, this);
        setEditTextScannerEvents(et_number, this);

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        ArrayList<PickOrderBean.SkuBean> skus = pickOrderBean.getSkus();
        btn_confirm = findViewById(R.id.btn_confirm);
        for (PickOrderBean.SkuBean sku : pickOrderBean.getSkus()) {
            pickQty += sku.getPickQty();
            pickedQty += sku.getPickedQty();
        }
        if (pickQty > 0) {
            btn_confirm.setEnabled(true);
        }

        adapter = new PickGoodListAdapter(this, skus);
        recyclerView.setAdapter(adapter);
        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RemindDialog remindDialog = new RemindDialog(PickGoodsDetailActivity.this);
                remindDialog.setTitle("确认完成拣选");
                remindDialog.setContent("已拣选/总应拣选数：" + pickedQty + "/" + pickQty + "\n请确认是否部分拣选？\n提示：点击确认后，将不能继续操作当前拣选单");
                remindDialog.setShowCancelButton();
                remindDialog.setListener(new RemindDialog.OnConfirmClickListener() {
                    @Override
                    public void onConfirmClick() {
                        pickUpdate("2");
                    }
                });
                remindDialog.show();

            }
        });

        btn_submit = findViewById(R.id.btn_submit);
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pickUpdate("1");
            }
        });

        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RemindDialog remindDialog = new RemindDialog(PickGoodsDetailActivity.this);
                remindDialog.setNoTitle();
                remindDialog.setContent("退出后，拣选明细不会被保存，请确认退出操作");
                remindDialog.setShowCancelButton();
                remindDialog.setListener(new RemindDialog.OnConfirmClickListener() {
                    @Override
                    public void onConfirmClick() {
                        finish();
                    }
                });
                remindDialog.show();
            }
        });

        pickType = getIntent().getIntExtra("pickType", 0);
        if (pickType == 1) {
            et_number.setEnabled(false);
            et_number.setText("1");
        }
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (!(v instanceof EditText)) {
            return false;
        }
        EditText editText = (EditText) v;
        String input = editText.getText().toString().trim();
        if (TextUtils.isEmpty(input)) return false;
        if ((keyCode == KeyEvent.KEYCODE_SYSRQ || keyCode == KeyEvent.KEYCODE_ENTER) && event.getAction() == KeyEvent.ACTION_UP) {
            switch (v.getId()) {
                case R.id.et_locationCode:
                    boolean isExit = false;
                    for (PickOrderBean.SkuBean bean : pickOrderBean.getSkus()) {
                        if (input.equals(bean.getLocationCode())) {
                            CommonUtil.requestFocusAndClearText(et_skuCode);
                            isExit = true;
                        }
                    }

                    if (!isExit) {
                        SpeakUtils.speakWithToast(PickGoodsDetailActivity.this, "拣选库位不属于此单，请检查", true, false);
                        CommonUtil.requestFocusAndClearText(et_locationCode);
                    }
                    break;
                case R.id.et_skuCode:
                    String locationCode = et_locationCode.getText().toString().trim();
                    if (TextUtils.isEmpty(locationCode)) {
                        SpeakUtils.speakWithToast(PickGoodsDetailActivity.this, "请先输入拣选库位", true, false);
                        CommonUtil.requestFocusAndClearText(et_locationCode);
                    }

                    boolean isExitSku = false;
                    for (int i = 0; i < pickOrderBean.getSkus().size(); i++) {
                        PickOrderBean.SkuBean bean = pickOrderBean.getSkus().get(i);
                        //如果库位和sku都输入正确，再增加拣选数量
                        if (locationCode.equals(bean.getLocationCode()) && input.equals(bean.getSkuCode())) {
                            isExitSku = true;
                            selectedSkuBean = bean;
                            //滚动到item
                            recyclerView.smoothScrollToPosition(i);
                            adapter.setOpinionPosition(i);
                            adapter.notifyDataSetChanged();
                            if (pickType == 1) {
                                addPickNum(1);
                            } else {
                                CommonUtil.requestFocusAndClearText(et_number);
                            }
                        }
                    }
                    if (!isExitSku) {
                        SpeakUtils.speakWithToast(PickGoodsDetailActivity.this, "请确认扫描的商品和所在实际库位是否匹配", true, false);
                        CommonUtil.requestFocusAndClearText(et_skuCode);
                    }
                    break;
                case R.id.et_number:
                    try {
                        addPickNum(Integer.parseInt(input));
                    } catch (Exception e) {
                        e.toString();
                    }
                    break;
            }
        }
        return false;
    }

    private void addPickNum(int num) {
        if (selectedSkuBean == null) return;
        //如果数量超出了
        if (selectedSkuBean.getPickedQty() + num > selectedSkuBean.getPickQty()) {
            SpeakUtils.speakWithToast(PickGoodsDetailActivity.this, "拣选数量已超过未拣选的数量，请确认", true, false);
            //逐件聚焦sku输入框
            if (pickType == 1) {
                CommonUtil.requestFocusAndClearText(et_skuCode);
            } else {
                CommonUtil.requestFocusAndClearText(et_number);
            }
        } else {
            selectedSkuBean.setCurrentQty(selectedSkuBean.getCurrentQty() + num);
            selectedSkuBean.setPickedQty(selectedSkuBean.getPickedQty() + num);
            adapter.notifyDataSetChanged();

            CommonUtil.requestFocusAndClearText(et_skuCode);
            if (pickType == 0) et_number.setText("");

            btn_confirm.setEnabled(true);
            btn_submit.setEnabled(true);
            //每次增加数量之后检查是否完成此单拣选,完成则按钮可点击
            pickQty = 0;
            pickedQty = 0;
            for (PickOrderBean.SkuBean sku : pickOrderBean.getSkus()) {
                pickQty += sku.getPickQty();
                pickedQty += sku.getPickedQty();
            }
            isComplete = pickQty == pickedQty;
        }
    }

    @Override
    public void changeWarehouse(Warehouse warehouse) {

    }

    public void pickUpdate(String type) {

        MyObserver myObserver = new MyObserver(this) {
            @Override
            public void onSuccess(BaseResponse result) {
                SpeakUtils.onlyRing(PickGoodsDetailActivity.this, 2);
                finish();
            }

            @Override
            public void onFailure(BaseResponse result, String msg) {
                SpeakUtils.speakWithToast(PickGoodsDetailActivity.this, msg, true, false);
            }
        };

        pickOrderBean.setSupPackupForm(type);
        HttpUtils.request(Api.class)
            .baseNoResultMethod(ConstantUtil.PICK_UPDATE, pickOrderBean)
            .compose(RxHelper.observableIO2Main(this))
            .subscribe(myObserver);
    }

//    private void clearView() {
//        et_skuCode.setText("");
//        et_locationCode.setText("");
//        et_number.setText("");
//
//        pickOrderBean.getSkus().clear();
//        adapter.notifyDataSetChanged();
//        btn_confirm.setEnabled(false);
//    }
}
